package com.hejing.线程安全问题;

/**
 * ClassName: WindowTest
 * Package: com.hejing.线程安全问题
 * Description:
 *      使用实现Runnable的方式，实现卖票
 *      同时，使用Synchronized同步代码块解决上述卖票案例中出现的 错票重票问题。
 * @Author: HeJing
 * @Create: 2023-04-14 19:21
 * @Version: 1.0
 */
public class WindowWithSynchronizedTest {
    public static void main(String[] args) {

        SaleTicketWithSyn s1 = new SaleTicketWithSyn();
        Thread t1 = new Thread(s1);
        Thread t2 = new Thread(s1);
        Thread t3 = new Thread(s1);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SaleTicketWithSyn implements Runnable {
    int ticket = 100;
    Object obj = new Object();
    @Override
    public void run() {
        while(true) {
            try{
                Thread.sleep(10);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            synchronized(this) {
                if(ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "售票, 票号为: " + (101 - ticket));
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
























